package com.devbobcorn.misaka.blocks;

import net.minecraft.block.BlockState;
import net.minecraft.block.CakeBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;

public class MisakaCakeBlock extends CakeBlock {
    public MisakaCakeBlock(Properties settings) {
        super(settings);
    }

    @Override
    public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) {
        ItemStack itemstack = player.getItemInHand(hand);

        if (state.getValue(BITES) == 0 && itemstack.getItem() == Items.HONEYCOMB) {
            // Add candles to the cake
            world.setBlock(pos, ModBlocks.CANDLE_MISAKA_CAKE.get().defaultBlockState(), 3);
            return ActionResultType.SUCCESS;
        }

        if (world.isClientSide) {
            if (eatSlice(world, pos, state, player).consumesAction()) {
                return ActionResultType.SUCCESS;
            }

            if (itemstack.isEmpty()) {
                return ActionResultType.CONSUME;
            }
        }

        return eatSlice(world, pos, state, player);
    }

    // Can't directly use eat(...) method defined in CakeBlock.class, so we define a new one here
    public static ActionResultType eatSlice(IWorld world, BlockPos pos, BlockState state, PlayerEntity player) {
        if (!player.canEat(false)) {
            return ActionResultType.PASS;
        } else {
            player.awardStat(Stats.EAT_CAKE_SLICE);
            player.getFoodData().eat(2, 0.1F);
            int i = state.getValue(BITES);
            if (i < 6) {
                world.setBlock(pos, state.setValue(BITES, Integer.valueOf(i + 1)), 3);
            } else {
                world.removeBlock(pos, false);
            }

            return ActionResultType.SUCCESS;
        }
    }
}
